package com.sxkf.template.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxkf.core.third.verify.ContextCheckUtil;
import com.sxkf.template.constants.CommonConstants;
import com.sxkf.template.entity.*;
import com.sxkf.template.mapper.*;
import com.sxkf.template.service.PostNoticeService;
import com.sxkf.template.service.PostService;
import com.sxkf.template.service.TopicService;
import com.sxkf.template.utils.TencentMapUtil;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.exception.SxkfExceptionEnum;
import org.jeecg.common.util.CheckEmptyUtil;
import org.jeecg.common.util.RedisUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户帖子 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-08-20 11:48:57
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    @Resource
    private PostLikeMapper postLikeMapper;
    @Resource
    private UserLikeMapper userLikeMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private AuditRecordMapper auditRecordMapper;
    @Resource
    private PostNoticeService postNoticeService;
    @Resource
    private UnlockPostMapper unlockPostMapper;
    @Resource
    private TencentMapUtil tencentMapUtil;
    @Resource
    private TopicService topicService;

    /**
     *
     * @param userId 用户id
     * @param type 1=推荐，2=关注,3=附近，4-在线
     */
    @Override
    public IPage<Post> pagePost(Integer pageNo, Integer pageSize, String userId, String type, String postType, String topicId, String postTitle, Double longitude, Double latitude) {
        //查询帖子
        LambdaQueryWrapper<Post> queryWrapper = new LambdaQueryWrapper<>();
        if (CheckEmptyUtil.isNotEmpty(postTitle)) {
            queryWrapper.like(Post::getTitle, postTitle);
        }
        switch (type){
            case "1":
                //暂时没啥逻辑
                break;
            case "2":
                List<UserLike> userLikes = userLikeMapper.selectList(new LambdaQueryWrapper<UserLike>()
                        .select(UserLike::getLikeUserId)
                        .eq(UserLike::getUserId, userId));
                if (CheckEmptyUtil.isNotEmpty(userLikes)){
                    List<String> likeUserIds = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
                    queryWrapper.in(Post::getUserId,likeUserIds);
                }
                break;
            case "3":
                String city = getCity(longitude,latitude);
//                String city = redisUtils.get(CommonConstants.LOCATION_CITY + userId);
//                if (null == city){
//                    throw new SxkfException(SxkfExceptionEnum.NO_LOCATION);
//                }
                queryWrapper.ne(Post::getUserId,userId)
//                        .eq(Post::getAddress,city);
                        .like(Post::getAddress,"\"city\""+":\""+city+"\"");
                break;
            case "4":
                //暂时没啥逻辑
                break;
            default:
                throw new SxkfException("参数错误");
        }
        queryWrapper
                .eq(Post::getState,"1")
                .eq(Post::getType,postType)
                .eq(CheckEmptyUtil.isNotEmpty(topicId),Post::getTopicId,topicId)
                .and(item -> item.eq(Post::getDisableViewIds,"").or().isNull(Post::getDisableViewIds).or().notLike(Post::getDisableViewIds,userId))
//                .notLike(Post::getDisableViewIds,userId)
                .and(item->item.eq(Post::getEnableViewIds,"").or().isNull(Post::getEnableViewIds).or().like(Post::getEnableViewIds,userId))
                .orderByDesc(Post::getCreateTime);

        IPage<Post> postPage = page(new Page<>(pageNo,pageSize),queryWrapper);
        //对查询出的数据进行处理
        handlePost(userId, type, postPage);
        return postPage;
    }

    private void handlePost(String userId, String type, IPage<Post> postPage) {
        if (postPage != null && CheckEmptyUtil.isNotEmpty(postPage.getRecords())){
            //String userJwd = redisUtil.get(CommonConstants.LOCATION_JWD + userId);
            postPage.getRecords().forEach(item->{
                //判断用户对此帖子是否点赞
                Long postLikeCount = postLikeMapper.selectCount(new LambdaQueryWrapper<PostLike>().eq(PostLike::getPostId, item.getId()).eq(PostLike::getUserId, userId));
                item.setIsLikePost(postLikeCount.intValue());

                //查询发贴人信息进行补充
                User user = userMapper.selectById(item.getUserId());

                if (null != user){
                    item.setNickName(user.getNickName());
                    item.setAvatar(user.getAvatar());
                    item.setGender(user.getGender());
                    item.setAge(user.getAge());
                }

                if (userId.equals(item.getUserId())){
                    item.setIsUnlock(true);
                    item.setIsLikeUser(0);
                }else {
                    //查询用户是否对发帖人进行关注
                    Long userLikeCount = userLikeMapper.selectCount(new LambdaQueryWrapper<UserLike>().eq(UserLike::getUserId, userId).eq(UserLike::getLikeUserId, item.getUserId()));
                    item.setIsLikeUser(userLikeCount.intValue());
//                if (type.equals("1")){
//                    Long userLikeCount = userLikeMapper.selectCount(new LambdaQueryWrapper<UserLike>().eq(UserLike::getUserId, userId).eq(UserLike::getLikeUserId, item.getUserId()));
//                    item.setIsLikeUser(userLikeCount.intValue());
//                }else {
//                    item.setIsLikeUser(1);
//                }

                    //查询是否解锁该帖子
                    if ("1".equals(item.getIsCharges())){
                        Long count = unlockPostMapper.selectCount(new LambdaQueryWrapper<UnlockPost>().eq(UnlockPost::getPostId, item.getId()).eq(UnlockPost::getUserId, userId));
                        item.setIsUnlock(count>0);
                    }
                }
            });
        }
    }

    @Override
    public IPage<Post> self(Integer pageNo,Integer pageSize,String userId) {
        Page<Post> result = page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<Post>()
                .eq(Post::getUserId, userId)
                // 动态
                .eq(Post::getType,"2")
                .orderByDesc(Post::getCreateTime));

        //对查询出的数据进行处理
        if (result != null && CheckEmptyUtil.isNotEmpty(result.getRecords())){
            //查询发贴人信息进行补充
            User user = userMapper.selectById(userId);

            List<String> topicIdList = result.getRecords().stream().map(Post::getTopicId).collect(Collectors.toList());
            List<Topic> topicList = topicService.listByIds(topicIdList);
            Map<String, String> topicTitleMap = topicList.stream().collect(Collectors.toMap(Topic::getId, Topic::getTitle));

            result.getRecords().forEach(item->{
                //判断用户对此帖子是否点赞
                Long postLikeCount = postLikeMapper.selectCount(new LambdaQueryWrapper<PostLike>()
                        .eq(PostLike::getPostId, item.getId())
                        .eq(PostLike::getUserId, userId));
                item.setIsLikePost(postLikeCount.intValue());
                // 填充topicTitle
                item.setTopicTitle(topicTitleMap.get(item.getTopicId()));

                if (null != user){
                    item.setNickName(user.getNickName());
                    item.setAvatar(user.getAvatar());
                    item.setGender(user.getGender());
                }

                //查询用户是否对发帖人进行关注
                item.setIsLikeUser(0);
            });
        }
        return result;
    }

    @Override
    public IPage<Post> pageSelfInterPost(Integer pageNo,Integer pageSize,String userId) {
        Page<Post> result = page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<Post>()
                .eq(Post::getUserId, userId)
                // 动态
                .eq(Post::getType,"1")
                .orderByDesc(Post::getCreateTime));

        //对查询出的数据进行处理
        if (result != null && CheckEmptyUtil.isNotEmpty(result.getRecords())){
            //查询发贴人信息进行补充
            User user = userMapper.selectById(userId);

            List<String> topicIdList = result.getRecords()
                    .stream()
                    .map(Post::getTopicId)
                    .collect(Collectors.toList());
            List<Topic> topicList = topicService.list(new LambdaQueryWrapper<Topic>()
                    .select(Topic::getId, Topic::getTitle)
                    .in(Topic::getId, topicIdList));

            Map<String, String> topicTitleMap = topicList.stream()
                    .collect(Collectors.toMap(Topic::getId, Topic::getTitle));


            result.getRecords().forEach(item->{
                //判断用户对此帖子是否点赞
                Long postLikeCount = postLikeMapper.selectCount(new LambdaQueryWrapper<PostLike>().eq(PostLike::getPostId, item.getId()).eq(PostLike::getUserId, userId));
                item.setIsLikePost(postLikeCount.intValue());
                // 填充topicTitle
                item.setTopicTitle(topicTitleMap.get(item.getTopicId()));
                if (null != user){
                    item.setNickName(user.getNickName());
                    item.setAvatar(user.getAvatar());
                    item.setGender(user.getGender());
                }

                //查询用户是否对发帖人进行关注
                item.setIsLikeUser(0);
            });
        }
        return result;
    }

    @Override
    public void add(Post post) {
        post.init();

//        check(post);

        post.setState("1");
//        post.setAddress(redisUtils.get(CommonConstants.LOCATION_CITY+post.getUserId()));
//        post.setJwd(redisUtils.get(CommonConstants.LOCATION_JWD+post.getUserId()));
        save(post);

        //提醒谁看
        if (CheckEmptyUtil.isNotEmpty(post.getRemindIds())){
            List<String> userIds = Collections.singletonList(post.getRemindIds());
            String[] split = post.getPictureJson().split(",");
//            List<JSONObject> pics = JSON.parseArray(post.getPictureJson(), JSONObject.class);
//            List<String> pics = JSON.parseArray(post.getPictureJson(), String.class);
            List<PostNotice> postNotices = userIds.stream().map(item -> {
                PostNotice postNotice = new PostNotice();
                postNotice.setPostId(post.getId());
                postNotice.setPostPicture(split[0]);
//                postNotice.setPostPicture(pics.get(0).getString("url"));
                postNotice.setUserId(item);
                postNotice.setType("3");
                postNotice.setState("0");
                return postNotice;
            }).collect(Collectors.toList());
            postNoticeService.saveBatch(postNotices);
        }
    }

    @Override
    public IPage<Post> interactionPage(Integer pageNo, Integer pageSize, String userId, String postTitle, String type, String address, String topicId, Double longitude, Double latitude) {

        //查询帖子
        LambdaQueryWrapper<Post> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Post::getState,"1").eq(Post::getType,"1");
        if (CheckEmptyUtil.isNotEmpty(postTitle)){
            queryWrapper.like(Post::getTitle, postTitle);
        }
//        switch (type){
//            case "1":
//                //暂时没啥逻辑
//                break;
//            case "2":
//                List<UserLike> userLikes = userLikeMapper.selectList(new LambdaQueryWrapper<UserLike>()
//                        .select(UserLike::getLikeUserId)
//                        .eq(UserLike::getUserId, userId));
//                if (CheckEmptyUtil.isNotEmpty(userLikes)){
//                    List<String> likeUserIds = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
//                    queryWrapper.in(Post::getUserId,likeUserIds);
//                }
//                break;
//            case "3":
//                String city = redisUtils.get(CommonConstants.LOCATION_CITY + userId);
//                if (null == city){
//                    throw new SxkfException(SxkfExceptionEnum.NO_LOCATION);
//                }
//                queryWrapper.ne(Post::getUserId,userId)
//                        .eq(Post::getAddress,city);
//                break;
//            case "4":
//                //暂时没啥逻辑
//                break;
//            default:
//                throw new SxkfException("参数错误");
//        }
        switch (type){
            case "1":

                // 距离最近
                String city = getCity(longitude,latitude);
//                String city = redisUtils.get(CommonConstants.LOCATION_CITY + userId);
//                if (null == city){
//                    throw new SxkfException(SxkfExceptionEnum.NO_LOCATION);
//                }
                queryWrapper.ne(Post::getUserId,userId)
//                        .eq(Post::getAddress,city);
                        .like(Post::getAddress,"\"city\""+":\""+city+"\"");
                break;
            case "2":
                // 最新发布
                queryWrapper.orderByDesc(Post::getCreateTime);break;

        }
        if (CheckEmptyUtil.isNotEmpty(address)){
            queryWrapper.eq(Post::getAddress, address);
        }
        if (CheckEmptyUtil.isNotEmpty(topicId)){
            queryWrapper.eq(Post::getTopicId,topicId);
        }

        Page<Post> page = page(new Page<>(pageNo, pageSize), queryWrapper);
        //对查询出的数据进行处理
        handlePost(userId, type, page);

        return page;
    }

    private String getCity(Double longitude, Double latitude) {

        if (CheckEmptyUtil.isEmpty(latitude) || CheckEmptyUtil.isEmpty(longitude)){
            throw new SxkfException(SxkfExceptionEnum.NO_LOCATION);
        }
        String aMapByLngAndLat = null;
        try {
            aMapByLngAndLat = tencentMapUtil.getAMapByLngAndLat(longitude+"", latitude+"");
            String[] split = aMapByLngAndLat.split("-");

            return split[2];
        } catch (Exception e) {
            log.error("腾讯地图异常");
            throw new SxkfException("定位 出错");
        }

    }

    private void check(Post post) {
        if (CheckEmptyUtil.isNotEmpty(post.getTitle())){
            Boolean result = ContextCheckUtil.checkText(post.getTitle());
            if (!result){
                throw new SxkfException("标题中含有非法内容");
            }
        }
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setSource("1");
        auditRecord.setSourceId(post.getId());
        auditRecord.setState("0");
        if (CheckEmptyUtil.isNotEmpty(post.getPictureJson())){

            List<JSONObject> imgs = JSON.parseArray(post.getPictureJson(), JSONObject.class);
            imgs.forEach(item->{
                String reqId = ContextCheckUtil.checkImg(item.getString("url"));
                auditRecord.setType("1");
                auditRecord.setTypeId(reqId);
            });
        }

//        if (CheckEmptyUtil.isNotEmpty(post.getPictures())){
//            post.getPictures().forEach(item->{
//                String reqId = ContextCheckUtil.checkImg(item);
//                auditRecord.setType("1");
//                auditRecord.setTypeId(reqId);
//            });
//        }

        if (CheckEmptyUtil.isNotEmpty(post.getVideoUrl())){
            String taskId = ContextCheckUtil.checkVideo(post.getVideoUrl());
            auditRecord.setType("2");
            auditRecord.setTypeId(taskId);
        }
        auditRecordMapper.insert(auditRecord);
    }
}
